package com.houmeiyuan.huiguniang.ctrl;

import com.houmeiyuan.huiguniang.common.Result;

import com.houmeiyuan.huiguniang.modles.domain.WxUser;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * Controller 基类
 */
@RefreshScope
public class BaseCtrl {
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    private final String USER_PREFIX = "wxuser:";
    /**
     * 处理成功时的返回
     *
     * @param o 返回的结果集
     * @return Result
     */
    protected Result send(Object o) {
        Result ret = new Result();
        ret.setResult(o);
        return ret;
    }

    /**
     * 非正常情况的返回
     *
     * @param code    错误码
     * @param message 错误信息
     * @return Result
     */
    protected Result send(int code, String message) {
        Result ret = new Result();
        ret.setStatus(code, message);
        return ret;
    }

    /**
     * 特殊情况的反馈
     *
     * @param o       结果集
     * @param code    状态码
     * @param message 状态信息
     * @return Result
     */
    protected Result send(Object o, int code, String message) {
        Result ret = new Result();
        ret.setStatus(code, message);
        ret.setResult(o);
        return ret;
    }
    /**
     * 获取登录的用户信息
     *
     * @param
     * @return
     */
    public WxUser getUserFromSession(String phone) {

      WxUser user = (WxUser)redisTemplate.opsForValue().get(USER_PREFIX+phone);

        return user;
    }
    /**
     * 写入用户信息到 redis
     *
     *@param token
     * @param user
     */
    public void setUserToSession(String token, WxUser user) {
        redisTemplate.opsForValue().set(USER_PREFIX+token , user,365, TimeUnit.DAYS);
    }
    /**
     * 写入数据到session
     * @param name
     * @param value
     * @param request
     */
    public void setValueToSession(String name, String value, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(60 * 30);
        session.setAttribute(name, value);
    }
    /**
     * 从session读取数据
     * @param name
     * @param request
     * @return
     */
    public String getValueFromSession(String name, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String value = (String) session.getAttribute(name);
        return value;
    }
}
